package com.cilico.waterfall;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import android.graphics.Paint;
import android.graphics.drawable.Drawable;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import com.cilico.R;
import com.cilico.shopcart.ShopCart;
import com.cilico.shopcart.ShopCartInfo;
import com.cilico.utils.PackageManagerAndroid;
import com.cilico.utils.Utils;
import com.cilico.view.BaseView;
import com.cilico.view.DetailView;
import com.cilico.waterfall.ImageLoadUtil.LoadImageListener;

public class WaterfallAdapter extends BaseAdapter {
	BaseView bv_;
	private LayoutInflater inflater;
	private List<ItemBase> items_; // 封装好的所有item报文
	private Waterfall myListView_;
	private ImageLoadUtil loader;
	ShopCart shopCart_;
	/**点餐，选中的数据*/
	List <ItemBase> checkedData_ = new ArrayList <ItemBase>();

	public WaterfallAdapter(BaseView bv, List<ItemBase> items, Waterfall myListView) {
		bv_ = bv;
		inflater = LayoutInflater.from(bv);
		items_ = items;
		myListView_ = myListView;
		loader = new ImageLoadUtil();
		loader.setUnLock(true);
	}
	
	private void intit(){
		//每一次初始化要清空数据
		BaseView.mid_.pm_.SAVEPROPERTYDB_.save(PackageManagerAndroid.SHOPCART_DB, "");
		BaseView.mid_.pm_.SAVEPROPERTYDB_.save(PackageManagerAndroid.SHOPCART_REAL_DB, "");
//		String checkdata = BaseView.mid_.pm_.SAVEPROPERTYDB_.get(PackageManagerAndroid.SHOPCART_REAL_DB);
//		checkedData_ = Utils.parseJson(checkdata, "3");
//		
	}

	public int getCount() {
		return items_.size();
	}

	public Object getItem(int position) {
		return items_.get(position);
	}

	public long getItemId(int position) {
		return position;
	}

	public View getView(int position, View convertView, ViewGroup parent) {
		ViewHolder holder;
		if (myListView_.infoType_.equals("1")) {
			/* 优惠 */
			convertView = inflater.inflate(R.layout.waterfall_item1, null);
		} else if (myListView_.infoType_.equals("2")) {
			/* 餐馆 */
			convertView = inflater.inflate(R.layout.waterfall_item2, null);
		} else if (myListView_.infoType_.equals("3")) {
			/* 菜品 */
			convertView = inflater.inflate(R.layout.waterfall_item3, null);
		} else if (myListView_.infoType_.equals("4")) {
			/* 待处理 */
			convertView = inflater.inflate(R.layout.waterfall_item, null);
		}
		holder = new ViewHolder();
		ItemBase data = items_.get(position);
		if (data != null) {
			makeData(data, holder, convertView,position);
		}
		return convertView;
	}
	/**
	 * 组装分类数据
	 * @author lvke
	 * Email: lvke@live.cn
	 * 2013-12-13下午2:24:56
	 * @param item
	 * @param holder
	 */
	private void makeData(ItemBase item,final ViewHolder holder,View convertView,int position){
		if (myListView_.infoType_!= null){
			holder.pic = (ImageView) convertView.findViewById(R.id.item_pic);
			holder.pic.setOnClickListener(new Click(item));
			if (myListView_.infoType_.trim().equals("1")) {
				//优惠列表
				holder.name = (TextView) convertView.findViewById(R.id.item_name);
				holder.costPrice = (TextView) convertView.findViewById(R.id.item_costPrice);
				holder.preferentialPrice = (TextView) convertView.findViewById(R.id.item_preferentialPrice);
				holder.peopleNum = (TextView) convertView.findViewById(R.id.item_peopleNum);
				holder.feedback = (TextView) convertView.findViewById(R.id.item_feedback);
				
				ItemInfo data = (ItemInfo)item;
				try {
					String id = data.getId();
					String name = data.getName();
					String imageUrl = data.getImageUrl();
					String costPrice = data.getCostPrice();
					String preferentialPrice = data.getPreferentialPrice();
					String peopleNum  = data.getPeopleNum();
					String feedback  = String.valueOf(data.getFeedback());
					
					if (null == name) {
						name = "";
					}
					if (null == imageUrl) {
						imageUrl = "local://waterfall_default.png";
					}
					if (null == costPrice) {
						costPrice = "";
					}
					if (null == preferentialPrice) {
						preferentialPrice = "";
					}
					if (null == peopleNum) {
						peopleNum = "";
					}
					if (null == feedback) {
						feedback = "";
					}
					holder.id = id;
					holder.name.setText(name);
					holder.pic.setTag(position);
					holder.costPrice.setText(costPrice + "元");
					holder.costPrice.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG | Paint.ANTI_ALIAS_FLAG);  // 设置中划线并加清晰 
					holder.preferentialPrice.setText(preferentialPrice + "元");
					holder.peopleNum.setText(peopleNum + "人订过");
					holder.feedback.setText(feedback + "分");
					
					final String tag = String.valueOf(position);
					loader.setOnLoadImageListener(tag,imageUrl, new LoadImageListener() {
						public void loadImage(Drawable imageDrawable) {
							holder.pic.setImageDrawable(imageDrawable);
							holder.pic.invalidate();
							myListView_.postInvalidate();
						}
					});
				} catch (Exception e) {
					e.printStackTrace();
				}
			} else if (myListView_.infoType_.trim().equals("2")) {
					//餐馆列表
					holder.name = (TextView) convertView.findViewById(R.id.item_name);
					holder.mealStyle = (TextView) convertView.findViewById(R.id.item_mealStyle);
					holder.address = (TextView) convertView.findViewById(R.id.item_address);
					holder.peopleNum = (TextView) convertView.findViewById(R.id.item_peopleNum);
					holder.feedback = (TextView) convertView.findViewById(R.id.item_feedback);
					
					ItemRestaurant data = (ItemRestaurant)item;
					try {
						String id = data.getId();
						String name = data.getName();
						String imageUrl = data.getImageUrl();
						String mealStyle = data.getMealStyle();
						String address = data.getAddress();
						String peopleNum  = data.getPeopleNum();
						String feedback  = String.valueOf(data.getFeedback());
						
						if (null == name) {
							name = "";
						}
						if (null == imageUrl || imageUrl.equals("")) {
							imageUrl = "local://waterfall_default.png";
						}
						if (null == mealStyle) {
							mealStyle = "";
						}
						if (null == address) {
							address = "";
						}
						if (null == peopleNum) {
							peopleNum = "";
						}
						if (null == feedback) {
							feedback = "";
						}
						holder.id = id;
						holder.name.setText(name);
						holder.pic.setTag(position);
						holder.mealStyle.setText(mealStyle);
						holder.address.setText(address);
						holder.peopleNum.setText(peopleNum + "人去过");
						holder.feedback.setText(feedback + "分");
						
						final String tag = String.valueOf(position);
						loader.setOnLoadImageListener(tag,imageUrl, new LoadImageListener() {
							public void loadImage(Drawable imageDrawable) {
								holder.pic.setImageDrawable(imageDrawable);
								holder.pic.invalidate();
								myListView_.postInvalidate();
							};
						});
					} catch (Exception e) {
						e.printStackTrace();
					}
				} else if (myListView_.infoType_.trim().equals("3")) {
					//菜品列表
					holder.book = (ImageView)convertView.findViewById(R.id.item_book);
					holder.name = (TextView) convertView.findViewById(R.id.item_menuName);
					//多少人点过
					holder.peopleNum = (TextView) convertView.findViewById(R.id.item_peopleNum);
					//原价
					holder.price = (TextView) convertView.findViewById(R.id.item_costPrice);
					//现价,没有就不显示
					holder.preferentialPrice = (TextView) convertView.findViewById(R.id.item_preferentialPrice);
					
					final ItemMeal data = (ItemMeal)item;
					// 根据缓存判断勾选框背景初始化
					if (null != ShopCart.order.get(data.getId())) {
						holder.book.setImageResource(R.drawable.checked);
					}else {
						holder.book.setImageResource(R.drawable.unchecked);
					}
					try {
						String restaurantId = data.getRestaurantId();
						String id = data.getId();
						String name = data.getMenuName();
						String imageUrl = data.getImageUrl();
						String price = data.getPrice();
						String peopleNum  = data.getPeopleNum();
						
						if (null == restaurantId) {
							restaurantId = "";
						}
						if (null == name) {
							name = "";
						}
						if (null == imageUrl) {
							imageUrl = "local://waterfall_default.png";
						}
						if (null == price) {
							price = "0";
						}
						if (null == peopleNum) {
							peopleNum = "";
						}
						holder.restaurantId = restaurantId;
						holder.id = id;
						holder.name.setText(name);
						holder.pic.setTag(position);
						holder.price.setText(price + "元");
						holder.peopleNum.setText(peopleNum + "人点过");
						
						final String tag = String.valueOf(position);
						loader.setOnLoadImageListener(tag,imageUrl, new LoadImageListener() {
							public void loadImage(Drawable imageDrawable) {
								holder.pic.setImageDrawable(imageDrawable);
								holder.pic.invalidate();
								myListView_.postInvalidate();
							}
						});
						
						// 预定
//						ClickLisenter clickLisenter = new ClickLisenter(data, holder);
//						holder.book.setOnClickListener(clickLisenter);
					} catch (Exception e) {
						e.printStackTrace();
					}
				
				}
			}
	}
	/**
	 * 菜品点餐的时候，响应事件
	 * @author lvke
	 * Email: lvke@live.cn
	 * 2014-2-10下午7:21:46
	 */
	private class ClickLisenter implements OnClickListener{
		ItemMeal data;
		ViewHolder holder;
		public ClickLisenter(ItemMeal data,ViewHolder holder){
			this.data = data;
			this.holder = holder;
		}
		public void onClick(View v) {
			boolean hasChecked = false;
			if (null != ShopCart.order.get(data.getId())) {
				hasChecked = true;
			}
			if (null != shopCart_) {
				/* 当取消勾选 */
				if (hasChecked) {
					holder.book.setImageResource(R.drawable.unchecked);
					// 在列表删除已点
					bv_.runOnUiThread(new Runnable() {

						@Override
						public void run() {
							// 小球减一
							shopCart_.cancelItem();
							// 删除缓存
							ShopCart.order.remove(data.getId());
						}
					});
				} else {
					/* 当勾选时 */
					holder.book.setImageResource(R.drawable.checked);

					bv_.runOnUiThread(new Runnable() {
						
						@Override
						public void run() {
							/* 为防止多次连击小球数字不对的问题出现，先判断该id是否已放进缓存 */
							boolean cached = false;
							Iterator iter = ShopCart.order.entrySet().iterator();
							while (iter.hasNext()) {
								Map.Entry entry = (Map.Entry) iter.next();
								String key = (String) entry.getKey();
								if (null != key && key.equals(data.getId())) {
									cached = true;
									break;
								}
							}
							if (!cached) {
								shopCart_.buyNum++;
								int[] start_location = new int[2];// 一个整型数组，用来存储按钮的在屏幕的X、Y坐标
								holder.book.getLocationInWindow(start_location);// 这是获取购买按钮的在屏幕的X、Y坐标（这也是动画开始的坐标）
								shopCart_.rollBall = new ImageView(bv_);// rollBall是动画的图片:一个小球
								shopCart_.rollBall.setImageResource(R.drawable.shopping_sign);// 设置rollBall的图片
								shopCart_.setAnimination(shopCart_.rollBall, start_location);// 开始执行动画
								
								// 把菜品id作为关键字保存，避免出现id不对的问题
								ShopCart.order.put(data.getId(), data);
								// 把当前item关键数据保存，用于本地listview显示
								ShopCartInfo cartInfo = new ShopCartInfo(
										data.getRestaurantId(),
										data.getId(),
										data.getMenuName(),
										data.getPrice(),
										"1"); // 默认数量为一份
								// 把当前item数据生成json并保存
								List <ItemBase> ls = new ArrayList <ItemBase>();
								ls.add(data);
								String json = Utils.makeJson(ls, "3");
								String oldShowValue = BaseView.mid_.pm_.SAVEPROPERTYDB_.get(PackageManagerAndroid.SHOPCART_DB);
								String oldRealValue = BaseView.mid_.pm_.SAVEPROPERTYDB_.get(PackageManagerAndroid.SHOPCART_REAL_DB);
								if (TextUtils.isEmpty(oldShowValue)) {
									BaseView.mid_.pm_.SAVEPROPERTYDB_.save(PackageManagerAndroid.SHOPCART_DB, cartInfo.toString());
									BaseView.mid_.pm_.SAVEPROPERTYDB_.save(PackageManagerAndroid.SHOPCART_REAL_DB, json);
								} else {
									BaseView.mid_.pm_.SAVEPROPERTYDB_.save(PackageManagerAndroid.SHOPCART_DB, oldShowValue + "@" + cartInfo.toString());
									BaseView.mid_.pm_.SAVEPROPERTYDB_.save(PackageManagerAndroid.SHOPCART_REAL_DB, oldRealValue + "@" + json);
								}
							}
							
							
						}
					});
				}
			}
			
		}
	}

	protected void resetViewHolder(ViewHolder holder) {
		holder.pic.setImageDrawable(null);
		holder.name.setText(null);
		holder.price.setText(null);
		holder.feedback.setVisibility(View.GONE);
//		holder.book.setVisibility(View.GONE);
	}

	static class ViewHolder {
		public String restaurantId;// 餐馆id
		public String id; // 产品id
		public ImageView pic; // 产品图片
		public TextView name; // 产品名字
		public TextView feedback; // 好评度
		public TextView address; // 餐馆地址
		public TextView peopleNum; // 多少人去过
		public TextView mealStyle; // 产品风格
		public TextView price; // 产品价格
		public TextView costPrice; // 原价
		public TextView preferentialPrice; // 现价
		public ImageView book; // 选择框
		public String amout; // 产品数量
	}
	
	private class Click implements OnClickListener{

		ItemBase itemBase;
		public Click(ItemBase o) {
			// TODO Auto-generated constructor stub
			itemBase = o;
		}
		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			if (null != bv_ && bv_ instanceof DetailView && itemBase!= null){
				String detailUrl_ = itemBase.getImgDetailUrl();
				
				if (detailUrl_ != null) {
					if (detailUrl_.indexOf("?") == -1)
						detailUrl_ = detailUrl_.concat("?");
					if (detailUrl_.endsWith("?") && itemBase.getId() != null){
						detailUrl_ = detailUrl_.concat("id="+itemBase.getId());
					}
					DetailView mbv = (DetailView)bv_;
					mbv.dealWithLink(detailUrl_, mbv, false);
				}
			}
		}
		
	}

	public ShopCart getShopCart() {
		return shopCart_;
	}

	public void setShopCart(ShopCart shopCart) {
		shopCart_ = shopCart;
	}

}
